package socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    /*
       java.net.Socket
       封装了TCP协议的通讯细节，使用它与远端计算机建立链接并进行可靠通讯
     */
    private Socket socket;

    /**
     * 构造方法，用来初始化客户端
     */
    public Client(){
        try{
            System.out.println("正在连接服务器...");
            socket = new Socket("176.201.104.24",8088);
//            socket = new Socket("localhost",8088);
            System.out.println("连接服务器成功！");
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 客户端开始工作的方法
     */

    public void start(){
        try{
            /*
               OutputStream getoutputStream()
               通过Socket获取的字节输出流写出的字节都会发送给链接的远端计算机
               而对方则可以通过Socket获取的输入流陆续读取到
             */
            OutputStream out = socket.getOutputStream();
//            out.write(1);
            Scanner scan = new Scanner(System.in);
            while(true){
                String list = scan.nextLine();
                if ("exit".equals(list)){
                    break;
                }
//            String list ="你好啊，鸡娃儿！";
            byte[] data = list.getBytes(StandardCharsets.UTF_8);
            out.write(data.length);
            out.write(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
